//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>
package org.jpgolay.wi.customer;

import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import org.jpgolay.gui.fixed.*;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.wi.persistence.ObjectCRUD;
import org.jpgolay.wi.salesperson.SalesPerson;
import org.jpgolay.wi.util.*;

// Referenced classes of package org.jpgolay.wi.customer:
//            CustomerGUI, CustomerCRUD, Customer
public class CustomerController extends CustomerGUI {

    private class MouseClickCustomerList extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                actionLoad((String) customerTable.getTable().getValueAt(customerTable.getTable().getSelectedRow(), 0));
            }
        }

        MouseClickCustomerList() {
        }
    }

    public CustomerController(Parameter param) {
        create = false;
        updateRowsTable = true;
        customerTable = null;
        write = false;
        this.param = param;
        crud = new ObjectCRUD();
        customerCrud = new CustomerCRUD();
        initLaw();
        initMenu();
        initIconBar();
        initField();
        initSalesPersonList();
        initSearch();
        initCustomerListTable();
    }

    private void initLaw() {
        write = true;
    }

    private void initMenu() {
        getMenuPanel().getExit().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionExit();
            }
        });
        getMenuPanel().getDelete().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionRemove();
            }
        });
        getMenuPanel().getHelp().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionHelp();
            }
        });
        getMenuPanel().getModify().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionModify();
            }
        });
        getMenuPanel().getNew().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionNew();
            }
        });
        getMenuPanel().getOpen().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionevent) {
            }
        });
        getMenuPanel().getPrint().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionPrint(true);
            }
        });
        getMenuPanel().getSave().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSave();
            }
        });
    }

    private void initIconBar() {
        getIconBarPanel().addAnswerListener(new AnswerListener() {
            public void create(AnswerEvent e) {
                actionNew();
            }

            public void open(AnswerEvent answerevent) {
            }

            public void modify(AnswerEvent e) {
                actionModify();
            }

            public void save(AnswerEvent e) {
                actionSave();
            }

            public void remove(AnswerEvent e) {
                actionRemove();
            }

            public void print(AnswerEvent e) {
                actionPrint(false);
            }

            public void help(AnswerEvent e) {
                actionHelp();
            }
        });
    }

    private void initField() {
        cleanField();
        setEnabledField(false);
        getIconBarPanel().setEnabledCreate(write);
        getIconBarPanel().setEnabledSave(false);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(false);
        getIconBarPanel().setEnabledPrint(false);
        getIconBarPanel().setEnabledOpen(false);
        getMenuPanel().getNew().setEnabled(write);
        getMenuPanel().getSave().setEnabled(false);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(false);
        getMenuPanel().getPrint().setEnabled(false);
        getMenuPanel().getOpen().setEnabled(false);
        create = false;
        salesPersonList = null;
        initSalesPersonList();
    }

    private void initSalesPersonList() {
        java.util.Collection c = crud.readAll(null, 9);
        if (c != null) {
            SalesPerson salesPerson = null;
            salesPersonList = new ArrayList(c);
            Iterator it = salesPersonList.iterator();
            String list[] = new String[salesPersonList.size()];
            salesPersonIdList = new HashMap();
            for (int i = 0; it.hasNext(); i++) {
                salesPerson = (SalesPerson) it.next();
                salesPersonIdList.put(salesPerson.getId(), new Integer(i));
                list[i] = salesPerson.getFirstname() + " " + salesPerson.getLastname();
            }

            setSalesPersonList(list);
        } else {
            setSalesPersonList(new String[]{
                        "aucun"
                    });
        }
    }

    private Object[][] getDiscountEmptyTable() {
        Object data[][] = new Object[3][8];
        for (int i = 0; i < data.length; i++) {
            if (i == 1) {
                data[i][0] = "AUCUNE";
            } else {
                data[i][0] = null;
            }
            data[i][1] = null;
            data[i][2] = null;
            data[i][3] = null;
            data[i][4] = null;
            data[i][5] = null;
            data[i][6] = null;
            data[i][7] = null;
        }

        return data;
    }

    private void initSearch() {
        getCustomerSearchBox().setList(new String[]{
                    "Code", "Nom", "Ville", "Commercial (nom)", "Commercial (code)", "Pr\351nom"
                });
        getCustomerSearchBox().setVal("");
        getCustomerSearchBox().setAdvanceSearch(getCustomerTable());
        getCustomerSearchBox().getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
        getCustomerSearchBox().getTextField().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
    }

    private void initCustomerListTable() {
        customerTable.setTypes(new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
                });
        customerTable.setLastColumnNotEditable(0);
        customerTable.setCellEditable(false);
        customerTable.setAlternateColor(WIUtil.CUSTOMER_LINE);
        customerTable.setColumnNames(new String[]{
                    "CODE", "NOM", "PRENOM", "VILLE", "COMMERCIAL"
                });
        customerTable.setPreferredColumnSize(new int[]{
                    40, 50, 40, 50, 30
                });
        actionSearch();
    }

    private TableViewer getCustomerTable() {
        if (customerTable == null) {
            customerTable = new TableViewer();
        }
        return customerTable;
    }

    private void actionExit() {
        setVisible(false);
    }

    private void actionRemove() {
        int reponse = JOptionPane.showConfirmDialog(null, "Etes-vous certain de vouloir suprimer ce Client ?", "Confirmation", 1, 2, null);
        switch (reponse) {
            case 0: // '\0'
                actionDelete();
            // fall through

            case -1:
            case 1: // '\001'
            case 2: // '\002'
            default:
                return;
        }
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.ifacile.com");
    }

    private void actionModify() {
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(true);
    }

    private void actionNew() {
        initField();
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        create = true;
    }

    private void actionPrint(boolean flag) {
    }

    private void actionSave() {
        if (create) {
            actionCreate();
        } else {
            actionUpdate();
        }
    }

    private void actionSearch() {
        StringBuffer sql = new StringBuffer();
        if (getCustomerSearchBox().getSelectedIndex() == 3) {
            sql.append("SELECT CUSTOMER.ID, CUSTOMER.LASTNAME, CUSTOMER.FIRSTNAME, CITY, SALESPERSON.LASTNAME FROM CUSTOMER, SALESPERSON");
        } else {
            sql.append("SELECT ID, LASTNAME, FIRSTNAME, CITY, SALESPERSONID FROM CUSTOMER");
        }
        switch (getCustomerSearchBox().getSelectedIndex()) {
            case 0: // '\0'
                if (getCustomerSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY ID");
                } else {
                    sql.append(" WHERE ID LIKE '");
                    sql.append(getCustomerSearchBox().getVal());
                    sql.append("%' ORDER BY ID");
                }
                break;

            case 1: // '\001'
                if (getCustomerSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY LASTNAME");
                } else {
                    sql.append(" WHERE LASTNAME LIKE '");
                    sql.append(getCustomerSearchBox().getVal());
                    sql.append("%' ORDER BY LASTNAME");
                }
                break;

            case 2: // '\002'
                if (getCustomerSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY CITY");
                } else {
                    sql.append(" WHERE CITY LIKE '");
                    sql.append(getCustomerSearchBox().getVal());
                    sql.append("%' ORDER BY CITY");
                }
                break;

            case 3: // '\003'
                if (getCustomerSearchBox().getVal().equals("")) {
                    sql.append(" WHERE SALESPERSONID=SALESPERSON.ID");
                    sql.append(" ORDER BY SALESPERSON.LASTNAME");
                } else {
                    sql.append(" WHERE SALESPERSONID=SALESPERSON.ID");
                    sql.append(" AND SALESPERSON.LASTNAME LIKE '");
                    sql.append(getCustomerSearchBox().getVal());
                    sql.append("%' ORDER BY SALESPERSON.LASTNAME");
                }
                break;

            case 4: // '\004'
                if (getCustomerSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY SALESPERSONID");
                } else {
                    sql.append(" WHERE SALESPERSONID LIKE '");
                    sql.append(getCustomerSearchBox().getVal());
                    sql.append("%' ORDER BY SALESPERSONID");
                }
                break;

            case 5: // '\005'
                if (getCustomerSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY FIRSTNAME");
                } else {
                    sql.append(" WHERE FIRSTNAME LIKE '");
                    sql.append(getCustomerSearchBox().getVal());
                    sql.append("%' ORDER BY FIRSTNAME");
                }
                break;

            default:
                if (getCustomerSearchBox().getVal().equals("")) {
                    sql.append(" ORDER BY ID");
                } else {
                    sql.append(" WHERE ID LIKE '");
                    sql.append(getCustomerSearchBox().getVal());
                    sql.append("%' ORDER BY ID");
                }
                break;
        }
        Object data[][] = customerCrud.getDataList(sql.toString());
        if (data != null) {
            customerTable.setData(data);
            customerTable.getTable().addMouseListener(new MouseClickCustomerList());
        } else {
            customerTable.setData(getEmptyTable());
        }
    }

    private Object[][] getEmptyTable() {
        Object data[][] = new Object[3][5];
        for (int i = 0; i < data.length; i++) {
            data[i][0] = null;
            if (i == 1) {
                data[i][1] = "AUCUN";
                data[i][2] = "CLIENT";
            } else {
                data[i][1] = null;
                data[i][2] = null;
            }
            data[i][3] = null;
            data[i][4] = null;
        }

        return data;
    }

    private void actionLoad(String pk) {
        customer = (Customer) crud.read(new Integer(pk), 8);
        if (customer != null) {
            initField();
            setLastnameValue(customer.getLastname());
            setStatusValue(customer.getStatus());
            setAddrLn1Value(customer.getAddrLn1());
            setAddrLn2Value(customer.getAddrLn2());
            setCityValue(customer.getCity());
            setCountryValue(customer.getCountry());
            setZipValue(customer.getZip());
            setFirstnameValue(customer.getFirstname());
            setStateValue(customer.getState());
            setTelValue(customer.getTel());
            setFaxValue(customer.getFax());
            setCelValue(customer.getCel());
            setEmailValue(customer.getEmail());
            setWebValue(customer.getWww());
            setBankValue(customer.getBank());
            setBankNumberValue(customer.getBankNumber());
            setCardName(customer.getCardName());
            setCardNumber(customer.getCardNumber());
            setCardExpiryDate(customer.getCardExpiryDate());
            setCardDigiCode(customer.getCardDigiCode());
            setNotesValue(customer.getNotes());
            setLastUserValue(customer.getLastUserId());
            setLastTimeValue(customer.getLastTime());
            setIdValue(customer.getId().toString());
            if (customer.getSalesPersonId() != null && customer.getSalesPersonId().intValue() != 0) {
                setSalesPersonIndex(((Integer) salesPersonIdList.get(customer.getSalesPersonId())).intValue());
            }
            if (customer.getPaymentBy() != null) {
                setPaymentBy(customer.getPaymentBy());
            }
            setTitle("CLIENT (CODE : " + customer.getId() + ")");
            getIconBarPanel().setEnabledModify(write);
            getIconBarPanel().setEnabledPrint(true);
            getMenuPanel().getModify().setEnabled(write);
            getMenuPanel().getPrint().setEnabled(true);
            create = false;
        }
    }

    private void actionUpdate() {
        if (verifyRequirement()) {
            customer.setLastname(getLastnameValue());
            customer.setStatus(getStatusValue());
            customer.setAddrLn1(getAddrLn1Value());
            customer.setAddrLn2(getAddrLn2Value());
            customer.setCity(getCityValue());
            customer.setCountry(getCountryValue());
            customer.setZip(getZipValue());
            customer.setFirstname(getFirstnameValue());
            customer.setState(getStateValue());
            customer.setTel(getTelValue());
            customer.setFax(getFaxValue());
            customer.setCel(getCelValue());
            customer.setEmail(getEmailValue());
            customer.setWww(getWebValue());
            customer.setBank(getBankValue());
            customer.setBankNumber(getBankNumberValue());
            customer.setCardName(getCardName());
            customer.setCardNumber(getCardNumber());
            customer.setCardExpiryDate(getCardExpiryDate());
            customer.setCardDigiCode(getCardDigiCode());
            customer.setNotes(getNotesValue());
            customer.setLastUserId(param.getUserId().toString());
            if (salesPersonList != null) {
                SalesPerson sp = (SalesPerson) salesPersonList.get(getSalesPersonIndex());
                customer.setSalesPersonId(sp.getId());
            }
            customer.setPaymentBy(getPaymentBy());
            crud.update(customer, 8);
            initField();
        }
    }

    private void actionCreate() {
        if (verifyRequirement()) {
            Integer pk = crud.create(8);
            if (pk != null) {
                customer = (Customer) crud.read(pk, 8);
                customer.setLastname(getLastnameValue());
                customer.setStatus(getStatusValue());
                customer.setAddrLn1(getAddrLn1Value());
                customer.setAddrLn2(getAddrLn2Value());
                customer.setCity(getCityValue());
                customer.setCountry(getCountryValue());
                customer.setZip(getZipValue());
                customer.setFirstname(getFirstnameValue());
                customer.setState(getStateValue());
                customer.setTel(getTelValue());
                customer.setFax(getFaxValue());
                customer.setCel(getCelValue());
                customer.setEmail(getEmailValue());
                customer.setWww(getWebValue());
                customer.setBank(getBankValue());
                customer.setBankNumber(getBankNumberValue());
                customer.setCardName(getCardName());
                customer.setCardNumber(getCardNumber());
                customer.setCardExpiryDate(getCardExpiryDate());
                customer.setCardDigiCode(getCardDigiCode());
                customer.setNotes(getNotesValue());
                customer.setLastUserId(param.getUserId().toString());
                if (salesPersonList != null) {
                    SalesPerson sp = (SalesPerson) salesPersonList.get(getSalesPersonIndex());
                    customer.setSalesPersonId(sp.getId());
                }
                customer.setPaymentBy(getPaymentBy());
                crud.update(customer, 8);
                initField();
            } else {
                JOptionPane.showMessageDialog(null, "Code Client refus\351 !\n(v\351rif\351 si ce code n'est pas d\351j\340 utilis\351)");
            }
        }
    }

    private void actionDelete() {
        crud.delete(customer.getId(), customer.getLastTime(), 8);
        initField();
    }

    private boolean verifyRequirement() {
        if (getNotesValue() != null && getNotesValue().length() > 250) {
            JOptionPane.showMessageDialog(null, "Commentaires trop long (maxi. 250 caract\350res) !");
            return false;
        }
        if (getLastnameValue().length() < 2 || getLastnameValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Nom obligatoire (mini. 2 caract\350res, maxi. 50 caract\350res) !");
            return false;
        }
        if (getCountryValue() != null && getCountryValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Pays trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getFirstnameValue() != null && getFirstnameValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Pr\351nom trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getCelValue() != null && getCelValue().length() > 20) {
            JOptionPane.showMessageDialog(null, "Portable trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getEmailValue() != null && getEmailValue().length() > 100) {
            JOptionPane.showMessageDialog(null, "Email trop long (maxi. 100 caract\350res) !");
            return false;
        }
        if (getFaxValue() != null && getFaxValue().length() > 20) {
            JOptionPane.showMessageDialog(null, "Fax trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getTelValue() != null && getTelValue().length() > 20) {
            JOptionPane.showMessageDialog(null, "T\351l\351phone trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getZipValue() != null && getZipValue().length() > 20) {
            JOptionPane.showMessageDialog(null, "Code postal trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getCityValue() != null && getCityValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Ville trop longue (maxi. 50 caract\350res) !");
            return false;
        }
        if (getAddrLn2Value() != null && getAddrLn2Value().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse ligne 2 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getAddrLn1Value() != null && getAddrLn1Value().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse ligne 1 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getCardName() != null && getCardName().length() > 20) {
            JOptionPane.showMessageDialog(null, "Nom de la carte trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getCardNumber() != null && getCardNumber().length() > 50) {
            JOptionPane.showMessageDialog(null, "N\260 de la carte trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getCardExpiryDate() != null && getCardExpiryDate().length() > 20) {
            JOptionPane.showMessageDialog(null, "WIDate expiration carte trop longue (maxi. 20 caract\350res) !");
            return false;
        }
        if (getCardDigiCode() != null && getCardDigiCode().length() > 20) {
            JOptionPane.showMessageDialog(null, "Digicode trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getBankNumberValue() != null && getBankNumberValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "N\260 compte trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getWebValue() != null && getWebValue().length() > 100) {
            JOptionPane.showMessageDialog(null, "Site web trop long (maxi. 100 caract\350res) !");
            return false;
        } else {
            return true;
        }
    }
    private ObjectCRUD crud;
    private CustomerCRUD customerCrud;
    private Parameter param;
    private boolean create;
    private boolean updateRowsTable;
    private Customer customer;
    private TableViewer customerTable;
    private HashMap salesPersonIdList;
    private ArrayList salesPersonList;
    private boolean write;
}
